package com.ikingtech.platform.service.system.organization.service;

import com.ikingtech.framework.sdk.component.api.CompOrganizationApi;
import com.ikingtech.framework.sdk.component.model.ComponentOrganization;
import com.ikingtech.framework.sdk.context.security.Me;
import com.ikingtech.framework.sdk.enums.component.PickerElementTypeEnum;
import com.ikingtech.framework.sdk.organization.model.OrganizationDTO;
import com.ikingtech.framework.sdk.utils.Tools;
import com.ikingtech.platform.service.system.organization.entity.OrganizationDO;
import lombok.RequiredArgsConstructor;

import java.util.List;

import static com.ikingtech.framework.sdk.context.constant.CommonConstants.ROOT_ORG_ID;

/**
 * @author tie yan
 */
@RequiredArgsConstructor
public abstract class AbstractCompOrganizationService implements CompOrganizationApi {

    private final OrganizationService service;

    @Override
    public ComponentOrganization getRootOrganization() {
        if (Tools.Str.isBlank(Me.tenantCode())) {
            return null;
        }
        OrganizationDO entity = this.service.getById(Tools.Str.join(Me.tenantCode(), ROOT_ORG_ID, "_"));
        if (null == entity) {
            return null;
        }
        return this.convert(Tools.Bean.copy(entity, OrganizationDTO.class));
    }

    @Override
    public List<ComponentOrganization> listByName(String name) {
        return this.convert(Tools.Coll.convertList(this.service.listByName(name, Me.tenantCode()), entity -> Tools.Bean.copy(entity, OrganizationDTO.class)));
    }

    @Override
    public List<ComponentOrganization> listByParentId(String parentId) {
        return this.convert(Tools.Coll.convertList(this.service.listByParentId(parentId), entity -> Tools.Bean.copy(entity, OrganizationDTO.class)));
    }

    private List<ComponentOrganization> convert(List<OrganizationDTO> organizations) {
        return Tools.Coll.convertList(organizations, this::convert);
    }

    private ComponentOrganization convert(OrganizationDTO organizations) {
        ComponentOrganization result = new ComponentOrganization();
        result.setElementType(PickerElementTypeEnum.ORGANIZATION);
        result.setElementId(organizations.getId());
        result.setElementName(organizations.getName());
        result.setFullPath(organizations.getFullPath());
        return result;
    }
}
